// 关键词模块 - 负责所有关键词相关的功能



// 生成关键词HTML
function generateKeywordsHtml(keywords) {
    if (!keywords || keywords.length === 0) {
        return '';
    }
    
    const keywordsHtml = keywords.map(keyword => 
        `<span class="badge bg-primary keyword-badge" onclick="searchByKeyword('${keyword}', 'mainSearchResultsList', 'mainSearchResults')">${keyword}</span>`
    ).join(' ');
    
    return `
        <div class="content-keywords mt-3">
            <h5>关键词:</h5>
            <div class="keywords">
                ${keywordsHtml}
            </div>
        </div>
    `;
}

// 生成关键词部分HTML
function generateKeywordsSection(keywords, content) {
    const list = (keywords && keywords.length)
        ? keywords.map(k => `<span class="badge bg-primary keyword-badge" onclick="searchByKeyword('${k}', 'mainSearchResultsList', 'mainSearchResults')">${escapeHtml(k)}</span>`).join(' ')
        : '<span class="text-muted">无关键词</span>';

    return `
        <div class="content-keywords mt-3 mb-4" id="keywords-section-${content.id}">
            <h5 class="d-flex align-items-center">关键词:</h5>
            <div class="keywords" id="keywords-list-${content.id}">
                ${list}
            </div>
        </div>
    `;
}

// ========== 关键词内联编辑（无按钮，直接在区域内增删） ==========
function initInlineKeywordsInlineMode(content) {
    const section = document.getElementById(`keywords-section-${content.id}`);
    const listEl = document.getElementById(`keywords-list-${content.id}`);
    if (!section || !listEl) return;

    // 记录归属用户，便于后续重渲染后保持可编辑状态
    section.dataset.userId = content.user_id || '';

    // 不显示旧的"编辑关键词"按钮（如果存在）
    const oldBtn = section.querySelector('button');
    if (oldBtn) oldBtn.remove();

    const canEdit = !!(currentUser && content && content.user_id && currentUser.user_id === content.user_id);
    if (!canEdit) return;

    // 给现有徽章加上删除"×"
    const badges = Array.from(listEl.querySelectorAll('.keyword-badge'));
    badges.forEach((badge, idx) => {
        // 记录原始关键字文本以便获取
        if (!badge.dataset.key) {
            badge.dataset.key = (badge.textContent || '').trim();
        }
        // 已经加过 × 的跳过
        if (!badge.querySelector('.kw-close')) {
            const close = document.createElement('span');
            close.className = 'kw-close ms-1';
            close.textContent = '×';
            close.style.cursor = 'pointer';
            close.onclick = function(ev) {
                ev.stopPropagation(); // 防止触发搜索
                removeKeywordInline(content.id, idx);
            };
            badge.appendChild(close);
        }
    });

    // 创建内联输入框（用于新增）
    let input = document.getElementById(`keywords-inline-input-${content.id}`);
    if (!input) {
        input = document.createElement('input');
        input.type = 'text';
        input.className = 'form-control form-control-sm mt-2';
        input.id = `keywords-inline-input-${content.id}`;
        input.placeholder = '点击此处输入新关键词，按回车添加';
        input.style.display = 'none';
        section.appendChild(input);
    input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            addKeywordInline(content.id);
            // 回车后隐藏输入框（无论是否添加成功或重复/为空）
            input.style.display = 'none';
        }
    });
    }

    // 点击关键词区域的空白处，显示并聚焦输入框
    section.onclick = function(e) {
        const t = e.target;
        const isBadge = t.classList.contains('keyword-badge') || t.closest('.keyword-badge');
        const isClose = t.classList.contains('kw-close');
        if (!isBadge && !isClose) {
            input.style.display = '';
            input.focus();
            e.stopPropagation(); // 阻止事件冒泡到document
        }
    };
    
    // 添加全局点击事件，点击其他区域时隐藏输入框
    if (!window._keywordInputHideHandlerAdded) {
        document.addEventListener('click', function(e) {
            // 获取所有可见的关键词输入框
            const visibleInputs = document.querySelectorAll('input[id^="keywords-inline-input-"]:not([style*="display: none"])');
            visibleInputs.forEach(input => {
                // 如果点击的不是输入框本身，则隐藏
                if (e.target !== input) {
                    input.style.display = 'none';
                }
            });
        });
        window._keywordInputHideHandlerAdded = true; // 标记已添加全局处理器，避免重复
    }
}

// 读取当前列表中的关键字
function getKeywordsFromList(contentId) {
    const listEl = document.getElementById(`keywords-list-${contentId}`);
    if (!listEl) return [];
    const badges = Array.from(listEl.querySelectorAll('.keyword-badge'));
    return badges.map(b => {
        if (!b.dataset.key) {
            b.dataset.key = (b.textContent || '').replace('×', '').trim();
        }
        return b.dataset.key;
    }).filter(Boolean);
}

// 重新渲染关键字徽章列表，并保持可编辑增强
function renderKeywordsList(contentId, keywords) {
    const listEl = document.getElementById(`keywords-list-${contentId}`);
    const section = document.getElementById(`keywords-section-${contentId}`);
    if (!listEl || !section) return;

    listEl.innerHTML = (keywords && keywords.length
        ? keywords.map(k => `<span class="badge bg-primary keyword-badge" onclick="searchByKeyword('${k}', 'mainSearchResultsList', 'mainSearchResults')">${escapeHtml(k)}</span>`).join(' ')
        : '<span class="text-muted">无关键词</span>');

    // 复用记录的用户ID以恢复可编辑增强
    const uid = section.dataset.userId;
    initInlineKeywordsInlineMode({ id: contentId, user_id: uid ? parseInt(uid) || uid : null });
}

// 统一提交关键词保存
async function postKeywords(contentId, keywords) {
    const response = await fetch(`/api/content/${contentId}/keywords`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ keywords })
    });
    return await response.json();
}

// 删除某个关键字（即时保存）
function removeKeywordInline(contentId, index) {
    const arr = getKeywordsFromList(contentId);
    if (index < 0 || index >= arr.length) return;
    arr.splice(index, 1);

    postKeywords(contentId, arr)
    .then(data => {
        if (data && data.success) {
            const next = Array.isArray(data.keywords) ? data.keywords : arr;
            renderKeywordsList(contentId, next);
        } else {
            alert((data && data.error) || '删除关键词失败');
        }
    })
    .catch(err => {
        console.error('删除关键词失败:', err);
        alert('删除关键词失败，请重试');
    });
}

// 新增关键字（回车即保存）
function addKeywordInline(contentId) {
    const input = document.getElementById(`keywords-inline-input-${contentId}`);
    const val = (input && input.value || '').trim();
    if (!val) return;

    const arr = getKeywordsFromList(contentId);
    // 大小写不敏感去重
    const lowers = arr.map(s => s.toLowerCase());
    if (lowers.includes(val.toLowerCase())) {
        if (input) input.value = '';
        return;
    }
    arr.push(val);

    postKeywords(contentId, arr)
    .then(data => {
        if (data && data.success) {
            const next = Array.isArray(data.keywords) ? data.keywords : arr;
            renderKeywordsList(contentId, next);
            if (input) {
                input.value = '';
                input.style.display = 'none';
            }
        } else {
            alert((data && data.error) || '新增关键词失败');
        }
    })
    .catch(err => {
        console.error('新增关键词失败:', err);
        alert('新增关键词失败，请重试');
    });
}

// ========== 关键词编辑 ==========
function generateKeywordsSection(keywords, content) {
    const list = (keywords && keywords.length)
        ? keywords.map(k => `<span class="badge bg-primary keyword-badge" onclick="searchByKeyword('${k}', 'mainSearchResultsList', 'mainSearchResults')">${escapeHtml(k)}</span>`).join(' ')
        : '<span class="text-muted">无关键词</span>';

    return `
        <div class="content-keywords mt-3 mb-4" id="keywords-section-${content.id}">
            <h5 class="d-flex align-items-center">关键词:</h5>
            <div class="keywords" id="keywords-list-${content.id}">
                ${list}
            </div>
        </div>
    `;
}


